/**
 * 个人中心Api
 * 获取用户、反馈相关的信息
 */
const db = require('../../config/db')
const jwt = require('jsonwebtoken')
const axios = require('axios')

// 微信小程序配置
const APPID = 'wx0355ea34a15c6b41';
const APPSECRET = '724a133cd300ceb5f4446584461d9bd3';
const USER_APPSECRET = 'Us' + APPSECRET + 'eR'

/**
 * 用户登录
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.login = async (req, res) => {
  const { code, nickName, avatarUrl } = req.body;
  console.log("code: " + code)
  console.log("nickName: " + nickName)
  console.log("avatarUrl: " + avatarUrl)

  if (!code) {
    return res.status(400).json({ code: 1, message: '缺少 code 参数' });
  }

  try {
    // 1. 用 code 换 openid
    const wxRes = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid: APPID,
        secret: APPSECRET,
        js_code: code,
        grant_type: 'authorization_code'
      }
    });

    const { openid } = wxRes.data;
    if (!openid) {
      return res.status(400).json({ code: 1, message: '获取 openid 失败', error: wxRes.data });
    }

    // 2. 查数据库用户是否存在
    const [rows] = await db.query('SELECT * FROM user WHERE open_id = ?', [openid]);

    if (rows.length === 0) {
      // 3. 新用户 → 插入昵称和头像
      await db.query(
        'INSERT INTO user (open_id, nickname, avatar_url) VALUES (?, ?, ?)',
        [openid, nickName || '', avatarUrl || '']
      );
    } else {
      // 更新昵称和头像
      await db.query(
        'UPDATE user SET nickname = ?, avatar_url = ? WHERE open_id = ?',
        [nickName || '', avatarUrl || '', openid]
      );
    }

    // 4. 生成 token（7 天有效）
    const token = jwt.sign(
      { openid },
      USER_APPSECRET, // 改成安全的随机密钥
      { expiresIn: '7d' }
    );

    res.json({
      code: 0,
      message: rows.length === 0 ? '新用户已注册' : '用户已登录',
      token
    });

  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 1, message: '服务器错误' });
  }
};


/**
 * 用户每次进入小程序，判断token是否有效
 * @param {*} req 
 * @param {*} res 
 */
exports.checkToken =  (req, res) => {
    try {
        const { token } = req.body;
        console.log('token: ' + token)
        jwt.verify(token, USER_APPSECRET, (err, decoded) => {
            if (err) {
              return res.json({ code: 1, message: 'token 无效' });
            }
            // console.log("openId: ", decoded.openid)
            // req.openId = decoded.openid
            res.json({ code: 0, message: 'token 有效', openid: decoded.openid });
        });
    } catch(err) {
        console.error(err);
        res.status(500).json({ code: 1, message: '服务器错误' });
    }
}

/**
 * 根据openId获取用户个人信息
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.getUserInfoById = async(req, res) => {
  try {
    const openId = req.openId
    console.log("openId: ", openId)
    const sql = `SELECT nickname, avatar_url, sex, age, favorite_sports, college, sport FROM user
                 where open_id = ?`
    const [rows] = await db.query(sql, [openId])
    if(rows.length == 0) {
      return res.status(201).json({"error": "没有找到该用户信息！"})
    }
    const data = rows[0]
    const nickname = data.nickname
    console.log("nickname: ", nickname)
    console.log("favorite_sports: ", data.favorite_sports)
    let favoriteSport = data.favorite_sports == undefined ? "" : data.favorite_sports
    console.log("favoriteSport1: ", favoriteSport)
    if(favoriteSport != "") {
      favoriteSport = favoriteSport.split(',')
    } 
    console.log("favoriteSport2: ", favoriteSport)
    const sex = data.sex
    const sexStr = sex === 1 ? '男' : (sex === 2 ? '女' : '未知')
    let college = data.college
    let sport = data.sport
    let team
    if(college == undefined || sport == undefined)
      team = ""
    else {
      if(college == "校队")
        college = '校'
      team = `${college}${sport}队`
    }

    res.status(200).json({
      nickname: data.nickname,
      avatarUrl: data.avatar_url,
      sex: sexStr,
      age: data.age,
      favoriteSports : favoriteSport,
      team: team
    })
  } catch(err) {
    console.log("getUserInfoById error", err)
    return res.status(500).json({ "error": "getUserInfoById error!"})
  }
}

